package com.doitedu;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

/**
 * @Date 2021/12/10
 * @Created by HANGGE
 * @Description
 * 监听节点数据的变化
 * shell  get  /a  watch
 */
public class C06_Watcher02 {
    public static void main(String[] args) throws  Exception{
        /**
         * 获取ZK的连接
         * 参数三  监听器    监听获取连接成功
         */
        ZooKeeper zk = new ZooKeeper(
                "linux01:2181,linux02:2181,linux03:2181",
                2000,
             null);
      // 获取值
        byte[] data = zk.getData("/a", new Watcher() {
            // 数值发生变化  会回调方法
            @Override
            public void process(WatchedEvent event) {
                try {
                    System.out.println("/a节点的数据发生变化....." + event.getType());
                    // 重新获取值
                    byte[] data1 = zk.getData("/a", this, null);
                    System.out.println("更新后的值是: "+new String(data1));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }, null);
        //打印值
        System.out.println("当前/a节点的值是: " +new String(data));
        Thread.sleep(Integer.MAX_VALUE);
       // zk.close();

    }
}
